<template>
  <div>
    <div id="cesiumContainer"></div>

    <!-- 弹出框样式 -->
    <div id="stateShow">
        <i class="top"></i>
        <div>标题：<span id="title"></span></div>
        <div>状态：<span id="state"></span></div>
        <div>信息：<span id="info"></span></div>
        <i class="bottom"></i>
    </div>

  </div>
</template>

<script>
import * as Cesium from 'cesium'
import 'cesium/Source/Widgets/widgets.css'
import { initCesium } from '../common/js/initCesium'
import { CesiumIonDefaultAccessToken, TianDiTuToken } from '../common/js/config'

let towns = [
     {"name":"卢嘴村","latitude":32.780137 , "longitude": 111.293217},
     {"name":"余家湾","latitude":32.76209 , "longitude": 111.258115},
     {"name":"王家岭","latitude":32.751385 , "longitude": 111.243585},
     {"name":"尚家店","latitude":32.761158 , "longitude": 111.31904},
     {"name":"寺沟","latitude":32.786691 , "longitude": 111.261758},
     {"name":"新店","latitude":32.7741 , "longitude": 111.311985},
     {"name":"观音庙","latitude":32.761714 , "longitude": 111.283269},
     {"name":"黑垭：","latitude":32.713213 , "longitude": 111.290038},
     {"name":"蒿坪镇","latitude":32.747975 , "longitude": 111.258358},
     {"name":"居委会","latitude":32.746294 , "longitude": 111.257488}
]

let that

export default {
  mounted() {
    let viewer = initCesium(Cesium)
    viewer._cesiumWidget._creditContainer.style.display = 'none' // 隐藏版权信息

    // 添加道路信息
    viewer.imageryLayers.addImageryProvider(
      new Cesium.WebMapTileServiceImageryProvider({
        url: "http://t0.tianditu.gov.cn/cia_w/wmts?tk=" + TianDiTuToken,
        layer: "cia",
        style: "default",
        tileMatrixSetID: "w",
        format: "tiles",
        maximumLevel: 18,
      })
    );

    // 绘制区域
    async function addGeojson(url) { 
      let result = await Cesium.GeoJsonDataSource.load(url);
      viewer.dataSources.add(result);
      console.log("-----result:" , result);
      console.log("-----result.entities:" , result.entities);
      console.log("-----result.entities.values:" , result.entities.values);
      let entities = result.entities.values;
      for (let i = 0; i < entities.length; i++) {
        let entity = entities[i];
        entity.polygon.material = Cesium.Color.fromRgba("#4000ff00");
        entity.polygon.extrudedHeight = Math.floor(200); // 高度随机数，单位是米
        entity.polyline.material = new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.fromCssColorString("#4000ff00"),
        });
      }
    }

    addGeojson("./data/haoping_left.json")
    addGeojson("./data/haoping_right.json")

    // 发光
    viewer.scene.postProcessStages.bloom.enabled = true

    // 设置视角高度范围
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 300; // 可以设置最小高度
    viewer.scene.screenSpaceCameraController.maximumZoomDistance = 100000; // 可以设置最大高度


    // 设置相机可移动范围的矩形边界
    var west = Cesium.Math.toRadians(111.2279051057111); // 西边界经度，转换为弧度
    var south = Cesium.Math.toRadians(29.68945429973172); // 南边界纬度，转换为弧度    // 32.68945429973172
    var east = Cesium.Math.toRadians(111.38010008467467); // 东边界经度，转换为弧度
    var north = Cesium.Math.toRadians(32.85772767224697); // 北边界纬度，转换为弧度
    var rectangle = Cesium.Rectangle.fromRadians(west, south, east, north);
    viewer.camera.changed.addEventListener(function() {
      var cameraPosition = viewer.camera.positionCartographic;
      if (!Cesium.Rectangle.contains(rectangle, cameraPosition)) {
          var newLongitude = Cesium.Math.clamp(cameraPosition.longitude, west, east);
          var newLatitude = Cesium.Math.clamp(cameraPosition.latitude, south, north);

          viewer.camera.setView({
              destination: Cesium.Cartesian3.fromRadians(newLongitude, newLatitude, viewer.camera.positionCartographic.height),
              orientation: {
              heading: 0, 
              pitch: 125, 
              roll: 0, 
            }
          });
      }
    });

    // 设置初始位置
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(111.304002621792835 , 32.573590985989345, 16000.0),
      orientation: {
        heading: 0, 
        pitch: 125, 
        roll: 0, 
      }
    });

    // 设置鼠标相关事件
    // 禁止左键拖动视角：false 就是禁止，true 就是允许
    viewer.scene.screenSpaceCameraController.enableTranslate = true;
    // 禁止左键拖动视角:false 就是禁止，true 就是允许
    viewer.scene.screenSpaceCameraController.enableRotate = true;
    // 禁止中键控制视角缩放:false 就是禁止，true 就是允许
    viewer.scene.screenSpaceCameraController.enableZoom = true;
    // 禁止中键旋转视角:false 就是禁止，true 就是允许
    viewer.scene.screenSpaceCameraController.enableTilt = false;
    // viewer.scene.screenSpaceCameraController.tiltEventTypes = [
    //   Cesium.CameraEventType.LEFT_DRAG,
    // ];
    // // 缩放设置 重新设置缩放成员
    // viewer.scene.screenSpaceCameraController.zoomEventTypes = [
    //   Cesium.CameraEventType.MIDDLE_DRAG,
    //   Cesium.CameraEventType.WHEEL,
    //   Cesium.CameraEventType.PINCH,
    // ];
    // // 平移 添加鼠标右键  鼠标右键平移
    // viewer.scene.screenSpaceCameraController.rotateEventTypes = [
    //   Cesium.CameraEventType.RIGHT_DRAG,
    // ];


    // 点击事件, 创建一个ScreenSpaceEventHandler实例
    let cartesian; // 射线与地球表面之间的交点
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    // 监听LEFT_CLICK事件
    handler.setInputAction(function (click) {
        // 使用pick方法检查点击位置是否有Entity
        that.get_coordinate(viewer, click)
        var pickedObject = viewer.scene.pick(click.position);
        if (Cesium.defined(pickedObject) && pickedObject.id) {
          document.getElementById('stateShow').style.display = "block";
          let ray = viewer.camera.getPickRay(click.position);
          cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          document.getElementById('title').innerHTML = pickedObject.id.data.title;
          document.getElementById('state').innerHTML = pickedObject.id.data.state;
          document.getElementById('info').innerHTML = pickedObject.id.data.info;
          // 实时更新位置
          viewer.scene.postRender.addEventListener(updatePosition);
        }else {
          document.getElementById('stateShow').style.display = "none";
          // 移除事件监听
          viewer.scene.postRender.removeEventListener(updatePosition);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


    // 位置更新
    function updatePosition() {
      // 将WGS84坐标中的位置转换为窗口坐标
      let windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, cartesian);
      // 数值是样式中定义的宽高
      if (windowPosition == undefined) return
      document.getElementById('stateShow').style.left = (windowPosition.x - (150 / 2)) + 'px'
      document.getElementById('stateShow').style.top = (windowPosition.y - 140) + 'px'
    }

    this.creat_point(viewer)

  },

  created(){
    that = this
  },

  methods: {
    /**
     * 异步加载并展示 GIF 图像
     * 
     * @returns {Promise<Cesium.Entity>} - 返回加载后的 Cesium Entity
     */
    creat_point(viewer) {
      for (let i = 0; i < towns.length; i++) {
        let town = towns[i]
        const billboard = viewer.entities.add({
          name: town.name,
          position: Cesium.Cartesian3.fromDegrees(town.longitude , town.latitude),
          billboard: {
            image: 'ic_location.png',
            scale: 1.0,
            scaleByDistance: new Cesium.NearFarScalar(
              200,
              0.3,
              10000,
              0.05,
              15000,
              0.03,
            ),
          },
          data: {
            title: '面图层',
            state: '显示',
            info: '这是一个面图层'
          }
        });
      }
    },

    get_coordinate(viewer, event) {
      let cartesian = viewer.camera.pickEllipsoid(event.position);
      let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
      let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
      let coordinate = {
          longitude: Number(lng.toFixed(6)),
          latitude: Number(lat.toFixed(6)),
      };
      console.log(coordinate);
    }

  } 


}
</script>

<style scoped lang="scss">

#cesiumContainer {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  overflow: hidden;
}


#stateShow {
    width: 150px;
    height: 100px;
    position: absolute;
    border: 0px solid #00bbff;
    top: 0;
    left: 0;
    display: none;
    background: rgba($color: #18363f, $alpha: 0.75);
    color: white;
    font-size: 0.65rem;
    overflow: hidden;
    padding: 1rem;

    &::before {
      content: ' ';
      position: absolute;
      width: 0.13rem;
      height: 100%;
      top: -100%;
      left: 0;
      background-image: linear-gradient(
        0deg,
        transparent,
        #74efff,
        transparent
      );
      animation: two 4s linear infinite;
    }
    &::after {
      content: ' ';
      position: absolute;
      width: 0.13rem;
      height: 100%;
      bottom: -100%;
      right: 0;
      background-image: linear-gradient(
        360deg,
        transparent,
        #74efff,
        transparent
      );
      animation: four 4s linear 2s infinite;
    }
    i {
      position: absolute;
      display: inline-block;
      height: 4px;
      width: 100%;
    }
    .bottom {
      bottom: 0;
      left: -100%;
      background-image: linear-gradient(
        270deg,
        transparent,
        #74efff,
        transparent
      );
      animation: one 4s linear 1s infinite;
    }
    .top {
      top: 0;
      right: -100%;
      background-image: linear-gradient(
        270deg,
        transparent,
        #74efff,
        transparent
      );
      animation: three 4s linear 3s infinite;
    }
  }

  @keyframes one {
    0% {
      left: -100%;
    }
    50%,
    100% {
      left: 100%;
    }
  }
   
  @keyframes two {
    0% {
      top: -100%;
    }
    50%,
    100% {
      top: 100%;
    }
  }
   
  @keyframes three {
    0% {
      right: -100%;
    }
    50%,
    100% {
      right: 100%;
    }
  }
   
  @keyframes four {
    0% {
      bottom: -100%;
    }
    50%,
    100% {
      bottom: 100%;
    }
  }


</style>